/*-----------------------------------------------File Info------------------------------------------------
** File Name:               buzz.c  
** Last modified date:      2016.07.22
** Last version:            V0.1
** Description:             
**--------------------------------------------------------------------------------------------------------            
** Created date:            2016.09.07
** author:                  YLY
** Version:                 V0.1
** Descriptions:            蜂鸣器控制
**--------------------------------------------------------------------------------------------------------
*/

/*************************************************************
* 	include 
* 	头文件	
*************************************************************/
/*   硬件相关头文件     */
//#include "bspTimer.h"
#include "bspPWM.h"
/* OS 相关头文件 */
#include "osInclude.h"

/*   用户头文件      */
#include "buzz.h"
#include "appGpio.h"


#if BEZZER_EN
static tsPwm gBuzzPwm = BUZZ_PWM;
tsBuzzerCtrl tgBuzzerCtrl;
uint16_t gBuzzerTimerId;

/*
 * 蜂鸣器响
 */
static void buzzerOn(void)
{
	pwmInit(&gBuzzPwm, 2000, 0.1f);
	//pwmEnable(&gBuzzPwm);
}

/*
 * 蜂鸣器不响
 */
static void buzzerOff(void)
{
	pwmDisable(&gBuzzPwm);
}

/*
 * 蜂鸣器初始化
 */
static void buzzerInit(void)
{
	pwmInit(&gBuzzPwm, 2700, 0.1f);
}

/*
 * 蜂鸣器定时器中断
 */
void buzzerTimer(void)
{
	static uint8_t buzz_status = 0;
	
	if(tgBuzzerCtrl.freq)			/* 用定时器控制蜂鸣器的次数 */	/* 2-> */
	{		
		if(tgBuzzerCtrl.interval)		/* 蜂鸣器响的时间和间隔时间 */	/* 0-> */
		{
			tgBuzzerCtrl.interval--;
		}
		else							/* 鸣叫时间或者间隔时间到 */
		{
			if(buzz_status)				/* 0 */				
				buzzerOff();
			else
				buzzerOn();		
			buzz_status = !buzz_status;
			tgBuzzerCtrl.freq--;			/* 1-> */
			if(0 == tgBuzzerCtrl.freq)	/* 鸣叫完 */
			{
				buzzerOff();
				buzz_status = 0;
				delTimer(buzzerTimer);	/* 删除定时器 */
			}
			else
			{
				tgBuzzerCtrl.interval = tgBuzzerCtrl.time;	/* 5	*/
			}
		}
	}
}

/*
 * 设置并起动蜂鸣器
 */
void buzzStart(uint16_t timeMs, uint8_t freq)
{
	static uint8_t buzzFitstUse=0;
	if(!buzzFitstUse)
	{
		buzzFitstUse = 1;		
		buzzerInit();
	}
	
	tgBuzzerCtrl.time = timeMs/10;  
	if(tgBuzzerCtrl.time<1)
		tgBuzzerCtrl.time = 1;
	tgBuzzerCtrl.freq = freq<<1;	/* x2 */
	/* 创建定时器,让定时器使用定时器控制蜂鸣器鸣叫 */
	createTimer(10, buzzerTimer);
}
#endif























